//
//  ViewController.m
//  Partie III
//
//  Created by Vincent Seguin on 12-01-31.
//  Copyright (c) 2012 ETS. All rights reserved.
//

#import "ViewController.h"

@implementation ViewController

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle



- (void)viewDidLoad
{
    [super viewDidLoad];
    arrAthlete = [[NSMutableArray alloc] init];
    btnCommencerDescente.enabled = YES;
    btnFinDescente.enabled = NO;
    btnDidNotFinish.enabled = NO;
    btnTerminer.enabled = NO;
	// Do any additional setup after loading the view, typically from a nib.
    

}

- (void)viewDidUnload
{
    txtNom = nil;
    txtPrenom = nil;
    txtPays = nil;
    lblFirst = nil;
    lblSecond = nil;
    lblThird = nil;
    btnCommencerDescente = nil;
    btnFinDescente = nil;
    btnDidNotFinish = nil;
    lblNombreAthleteRestant = nil;
    lblJuge1 = nil;
    lblJuge2 = nil;
    lblJuge3 = nil;
    lblJuge4 = nil;
    lblJuge5 = nil;
    lblJuge6 = nil;
    lblJuge7 = nil;
    stepperJuge1 = nil;
    stepperJuge2 = nil;
    stepperJuge3 = nil;
    stepperJuge4 = nil;
    stepperJuge5 = nil;
    stepperJuge6 = nil;
    stepperJuge7 = nil;
    btnEntrerScore = nil;
    lblAthleteEnCourse = nil;
    lblAthleteProchain1 = nil;
    lblAthleteProchain2 = nil;
    lblChrono = nil;
    gridAthlete = nil;
    btnTerminer = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return YES;
}

- (IBAction)btnInscriptionTouchDown:(id)sender {
    Athlete *athlete = [[Athlete alloc] init];
    [athlete setNom:[txtNom text]];
    [athlete setPrenom:[txtPrenom text]];
    [athlete setPays:[txtPays text]];
    [athlete setIsRacing:NO];
    [athlete setScore:[NSDecimalNumber decimalNumberWithString:@"-1"]];
    [arrAthlete addObject:athlete];
    [self updateClassement];
    [self updateAthletesSuivants];
    [self updateNombreAthleteRestant];
    [gridAthlete reloadData];
    NSLog (@"Value of my BOOL = %@", isRacing ? @"YES" : @"NO");
    if (!isRacing) {
        btnCommencerDescente.enabled = YES;
    }
    [txtNom setText:@""];
    [txtPrenom setText:@""];
    [txtPays setText:@""];
}

- (void)updateCounter:(NSTimer *)theTimer {
	count += 1;
    
    int sec = count % 60;
    int min = sec / 60;
    int hrs = min / 24;
    
	NSString *s = [[NSString alloc]
                   initWithFormat:@"%02d:%02d:%02d", hrs, min, sec];
	lblChrono.text = s;
}

- (IBAction)btnCommencerDescenteTouchDown:(id)sender {
    btnCommencerDescente.enabled = NO;
    btnFinDescente.enabled = YES;
    btnDidNotFinish.enabled = YES;
    startDate = [NSDate date];
    Athlete *athlete = [arrAthlete objectAtIndex:([arrAthlete count] - [self nombreAthleteNonTermine])];
    [athlete setIsRacing:YES];
    isRacing = YES;
    [self updateAthletesEnCourse];
    [self updateAthletesSuivants];
    
    [lblChrono setText:@"00:00:00"];
    //Set a timer
    count = 0;
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0f
                                             target:self
                                           selector:@selector(updateCounter:)
                                           userInfo:nil
                                            repeats:YES];
}

- (IBAction)btnFinDescenteTouchDown:(id)sender {
    btnCommencerDescente.enabled = NO;
    btnFinDescente.enabled = NO;
    btnDidNotFinish.enabled = NO;
    btnEntrerScore.enabled = YES;
    [lblAthleteEnCourse setText:(@"N/A")];
    duree = [startDate timeIntervalSinceNow];
    [timer invalidate];
    timer = nil;
    [lblChrono setText:@"00:00:00"];
}

- (IBAction)btnDidNotFinishTouchDown:(id)sender {
    btnCommencerDescente.enabled = NO;
    btnFinDescente.enabled = NO;
    btnDidNotFinish.enabled = NO;
    [lblAthleteEnCourse setText:(@"N/A")];
    duree = -1;
    [timer invalidate];
    timer = nil;
    [lblChrono setText:@"00:00:00"];
}

- (IBAction)btnEntrerScoreTouchDown:(id)sender {
    NSMutableArray *arrScoreVirage = [[NSMutableArray alloc] init];
    double score = 0;
    
    //Calcul Virage
    [arrScoreVirage addObject:[NSNumber numberWithDouble:[stepperJuge1 value]]];
    [arrScoreVirage addObject:[NSNumber numberWithDouble:[stepperJuge2 value]]];
    [arrScoreVirage addObject:[NSNumber numberWithDouble:[stepperJuge3 value]]];
    [arrScoreVirage addObject:[NSNumber numberWithDouble:[stepperJuge4 value]]];
    [arrScoreVirage addObject:[NSNumber numberWithDouble:[stepperJuge5 value]]];
    
    NSArray *arrScoreSorted = [arrScoreVirage sortedArrayUsingComparator:^(id a, id b) {
        return [a compare:b];
    }];;
    
    for (int i=1; i<4; i++) {
        score += [[arrScoreSorted objectAtIndex:i] doubleValue];
    }
    
    //Calcul sauts
    score += ([stepperJuge6 value] + [stepperJuge7 value]) / 2;
    
    //Calcul temps
    double scoreTemps = ((int)(29.22 - duree)/ 0.59) * 0.2 + 5.625;
    
    if(scoreTemps > 7.5) {
        scoreTemps = 7.5;
    } else if (scoreTemps < 0) {
        scoreTemps = 0;
    }
    
    score += scoreTemps;
    
    if (duree == -1) {
        score = 0;
    }
    
    //Modifie l'athlete qui vient de courser
    Athlete *athlete = [arrAthlete objectAtIndex:([arrAthlete count] - [self nombreAthleteNonTermine])];
    [athlete setScore:[NSDecimalNumber numberWithDouble:score]];
    [athlete setIsRacing:NO];
    isRacing = NO;
    
    //Update de boutons
    if ([self nombreAthleteNonTermine] > 0){
        
        btnCommencerDescente.enabled = YES;
    }
    btnEntrerScore.enabled = NO;
    
    NSArray *sortedArray;
        
    sortedArray = [arrAthlete sortedArrayUsingComparator:^(id a, id b) {
        NSDecimalNumber *first = [(Athlete*)a score];
        NSDecimalNumber *second = [(Athlete*)b score];
        return [second compare: first];
    }];
    
    NSUInteger position = [sortedArray indexOfObject:athlete] + 1;
        
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Classement" message:[NSString stringWithFormat:@"Vous êtes en position: %d", position] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
    
    [self updateClassement];
    [self updateNombreAthleteRestant];
    
    //NSLog(@"%d", [athlete score]);
    NSLog(@"%f", score);
}

- (IBAction)btnTerminerTouchDown:(id)sender {
    //TODO
    
    NSArray *sortedArray;
    
    sortedArray = [arrAthlete sortedArrayUsingComparator:^(id a, id b) {
        NSDecimalNumber *first = [(Athlete*)a score];
        NSDecimalNumber *second = [(Athlete*)b score];
        return [second compare:first];
    }];
    
    Athlete *first = nil, *second = nil, *third = nil;
    
    for (int i=0; i<3; i++) {
        if([arrAthlete count] <= i) break;
        Athlete *athlete = [sortedArray objectAtIndex:i];
        if([[athlete score] isEqual:[NSDecimalNumber decimalNumberWithString:@"-1"]]) break;
        
        if(i == 0) {
            first = athlete;
        }
        else if (i == 1) {
            second = athlete;
        }
        else if (i == 2) {
            third = athlete;
        }
    }
    
    NSString *gold = @"N/A", *silver = @"N/A", *bronze = @"N/A";
    
    if (first != nil) {
        if (second != nil) {
            if ([[first score] isEqual:([second score])]) {
                gold = [[first nom] stringByAppendingString:@" : GOLD"];
                silver = [[second nom] stringByAppendingString:@" : GOLD"];
            }
            else {
                gold = [[first nom] stringByAppendingString:@" : GOLD"];
                silver = [[second nom] stringByAppendingString:@" : SILVER"];
            }
            if (third != nil) {
                bronze = [[third nom] stringByAppendingString:@" : BRONZE"];
            }
        }
        else {
            gold = [[first nom] stringByAppendingString:@" : GOLD"];
        }
    }
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Podium" 
                                                    message:[NSString stringWithFormat:@"%@\n%@\n%@", 
                                                             gold, silver, bronze] 
                                                   delegate:self 
                                          cancelButtonTitle:@"OK" 
                                          otherButtonTitles:nil, nil];
    [alert show];
    
}

- (IBAction)stepperJuge1ValueChanged:(UIStepper *)sender {
    [lblJuge1 setText:[NSString stringWithFormat:@"Juge 1: %.01f", [sender value]]];
}

- (IBAction)stepperJuge2ValueChanged:(UIStepper *)sender {
    [lblJuge2 setText:[NSString stringWithFormat:@"Juge 2: %.01f", [sender value]]];
}

- (IBAction)stepperJuge3ValueChanged:(UIStepper *)sender {
    [lblJuge3 setText:[NSString stringWithFormat:@"Juge 3: %.01f", [sender value]]];
}

- (IBAction)stepperJuge4ValueChanged:(UIStepper *)sender {
    [lblJuge4 setText:[NSString stringWithFormat:@"Juge 4: %.01f", [sender value]]];
}

- (IBAction)stepperJuge5ValueChanged:(UIStepper *)sender {
    [lblJuge5 setText:[NSString stringWithFormat:@"Juge 5: %.01f", [sender value]]];
}

- (IBAction)stepperJuge6ValueChanged:(UIStepper *)sender {
    [lblJuge6 setText:[NSString stringWithFormat:@"Juge 6: %.01f", [sender value]]];
}

- (IBAction)stepperJuge7ValueChanged:(UIStepper *)sender {
    [lblJuge7 setText:[NSString stringWithFormat:@"Juge 7: %.01f", [sender value]]];
}

- (void)updateClassement {
    NSArray *sortedArray;
    
    sortedArray = [arrAthlete sortedArrayUsingComparator:^(id a, id b) {
        NSDecimalNumber *first = [(Athlete*)a score];
        NSDecimalNumber *second = [(Athlete*)b score];
        return [second compare:first];
    }];
    
    for (int i=0; i<3; i++) {
        if([arrAthlete count] > i) {
            Athlete *athlete = [sortedArray objectAtIndex:i];
            
            if(![[athlete score] isEqual:[NSDecimalNumber decimalNumberWithString:@"-1"]]) {
                 if(i == 0) {
                     [lblFirst setText:([athlete nom])];
                 }
                 else if (i == 1) {
                     [lblSecond setText:([athlete nom])];
                 }
                 else if (i == 2) {
                     [lblThird setText:([athlete nom])];
                 }
            }
        }
    }
}

- (void)updateNombreAthleteRestant {
    [lblNombreAthleteRestant setText:[NSString stringWithFormat:@"%d",[self nombreAthleteNonTermine]]];
    NSLog(@"%d", [arrAthlete count]);
    btnTerminer.enabled = ([self nombreAthleteNonTermine] == 0 && [arrAthlete count] > 0);
}

- (void)updateAthletesEnCourse {
    [lblAthleteEnCourse setText:(@"N/A")];
    for (Athlete *athlete in arrAthlete) {
        if ([athlete isRacing]) {
            [lblAthleteEnCourse setText:([athlete nom])];
            break;
        }
    }
}

- (void)updateAthletesSuivants {
    int i=0;
    [lblAthleteProchain1 setText:(@"N/A")];
    [lblAthleteProchain2 setText:(@"N/A")];
    for (Athlete *athlete in arrAthlete) {
        if([[athlete score] isEqual:[NSDecimalNumber decimalNumberWithString:@"-1"]]) {
            if (![athlete isRacing]) {
                i++;
                if (i == 1) {
                    [lblAthleteProchain1 setText:([athlete nom])];
                }
                else if (i == 2) {
                    [lblAthleteProchain2 setText:([athlete nom])];
                    break;
                }
            }
        }
    }
}

- (int)nombreAthleteNonTermine {
    int i = 0;
    for (Athlete *athlete in arrAthlete) {
        if([[athlete score] isEqual:[NSDecimalNumber decimalNumberWithString:@"-1"]]) {
            i++;
        }
    }
    
    return i;
}

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section {
    return [arrAthlete count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"test"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
                                     reuseIdentifier:@"test"];
    }
    NSUInteger row = [indexPath row];
    Athlete *athlete = [arrAthlete objectAtIndex:row];
    cell.textLabel.text = [NSString stringWithFormat:@"%@ %@ %@", [athlete prenom], [athlete nom], [athlete pays]];
    return cell;
}

@end
